package basic;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class Demo4 {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		if (args.length!=2) {
			System.err.println("user infos err: <inpath>,<outpath>");
			System.exit(-1);
		}
		@SuppressWarnings("deprecation")
		Job job = new Job(new Configuration(), "savg");
		job.setJarByClass(Demo4.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));//输入路径
		FileOutputFormat.setOutputPath(job,new Path(args[1]));//输出路径
		
		job.setMapperClass(amap.class);
		job.setReducerClass(areduce.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(DoubleWritable.class);
		job.waitForCompletion(true);
	}
	public static class amap extends Mapper<LongWritable,Text, Text,IntWritable>{
		Text name=new Text();
		IntWritable score=new IntWritable();
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			String[] line = value.toString().split(" ");
			name.set(line[0]);
			score.set(Integer.parseInt(line[1]));
			context.write(name, score);
		};
	}
	//map产生的中间结果，《张三，98，65，88》	
	public static class areduce extends Reducer<Text,IntWritable, Text,DoubleWritable>{
		protected void reduce(Text k2, java.lang.Iterable<IntWritable> values, org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,DoubleWritable>.Context context) throws java.io.IOException ,InterruptedException {
			double sum=0;
			double i=0;
			for (IntWritable score : values) {
				sum+=score.get();//总分
				i++;//考试科目的个数
			}
			double avgs=sum/i;
			context.write(k2,new DoubleWritable(avgs));
		};
	}

}
